﻿$.fn.dictcomplete = function (url, options) {
    var defaults = {
        showParent: false
    };

    options = $.extend(defaults, options);
    this.each(function () {
        var $this = $(this);
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json',
            success: function (data) {
                var source = $.map(data, function (item) {
                    return {
                        label: item.Name.Default,
                        ParentName: item.ParentName.Default,
                        Id: item.Id,
                        ParentId: item.ParentId
                    };
                });
                $this.autocomplete({
                    source: source,
                    select: function (event, ui) {
                        $this.val(ui.item.label);
                        options.change(event, ui);
                        return false;
                    },
                    maxItemsToShow: 15
                })
            .data("autocomplete")
            ._renderItem = function (ul, item) {
                var parent = '';
                if (options.showParent) {
                    parent = "<br /><span class='list-descr'>(" + item.ParentName + ")</span>";
                }

                return $('<li class="autocomplete"></li>')
                                .data("item.autocomplete", item)
                                .append("<a class='test'>" + item.label + parent + "</a>")
                                .appendTo(ul);
            };
            }
        });
    });
};

$.fn.dictselect = function (url, options) {
    var defaults = {
        setDefault: false,
        parentControl: null,
        //format item
        format: function (item) {
            return $("<option></option>")
                            .attr("value", item.Id)
                            .attr("valueid", item.Id)
                            .text(item.Name.Default);
        },
        //format url if 
        urlFormat: function () {
            var parentId = options.parentControl.val();
            return url.replace('0', parentId);
        },
        selectedValue: null,
        //if true, means that parents values are already loaded and we can load children by parent
        parentIsLoaded: false,
        //add additional option
        setOther: false
    };

    options = $.extend(defaults, options);
    if (options.parentControl) {
        var $this = $(this);

        options.parentControl.change(function () {
            var parentId = options.parentControl.val();
            if (parentId != '-1' && parentId != '') {
                var newUrl = options.urlFormat();
                options.parentIsLoaded = true;
                reloadDictSelect($this, newUrl, options);
            } else {
                if (options.setDefault) {
                    console.log("cleared");
                    $this.empty();
                    $this.append(getDefaultOption());
                    $this.trigger("change");
                }
            }
            
            return false;
        });
        if (!options.parentIsLoaded) {
            if (options.setDefault) {
                $this.empty();
                $this.append(getDefaultOption());
                $this.trigger("change");
            }
            return false;
        }
    }
    reloadDictSelect(this, url, options);
};

function reloadDictSelect(control, url, options) {
    control.each(function () {
        var $this = $(this);
        $.ajax({
            url: url,
            dataType: 'json',
            type: 'GET',
            success: function (data) {
                $this.empty();
                if (options.setDefault) {
                    $this.append(getDefaultOption());
                }
                $.each(data, function (idx, item) {
                    var formattedItem = options.format(item);
                    if (options.selectedValue != null & item.Id == options.selectedValue) {
                        $(formattedItem).attr("selected", "selected");
                    }
                    $this.append(formattedItem);
                });
                if (options.setOther) {
                    $this.append(getOtherOption());
                }
                $this.trigger("change");
            },
            error: ajaxError
        });
    });
}

$.fn.dictmultiselect = function (url, options) {
    var $this = $(this);
    var defaults = {
        values: '[]',
        checkAllText: 'Check all',
        uncheckAllText: 'Uncheck all',
        noneSelectedText: 'Select options',
        selectedText: '# selected'
    };
    options = $.extend(defaults, options);

    $.ajax({
        url: url,
        dataType: 'json',
        type: 'GET',
        success: function (data) {
            $this.empty();
            $.each(data, function (idx, item) {
                var option = $("<option></option>")
                    .attr("value", item.Id)
                    .attr("valueid", item.Id)
                    .text(item.Name.Default);
                if ($.inArray(item.Id, options.values) > -1) {
                    option.attr("selected", "selected");
                }
                $this.append(option);
            });
            $this.multiselect({
                checkAllText: options.checkAllText,
                uncheckAllText: options.uncheckAllText,
                noneSelectedText: options.noneSelectedText,
                selectedText: options.selectedText
            });
        }
    });
};

$.fn.groupedmultiselect = function (url, options) {
    var $this = $(this);
    var defaults = {
        values: '[]',
        checkAllText: 'Check all',
        uncheckAllText: 'Uncheck all',
        noneSelectedText: 'Select options',
        selectedText: '# selected'
    };
    options = $.extend(defaults, options);

    $.ajax({
        url: url,
        dataType: 'json',
        type: 'GET',
        success: function (data) {
            $this.empty();
            $.each(data, function (idx, item) {
                var group = $("<optgroup></optgroup>")
                                .attr("label", item.Group);
                if (item.SubGroups) {
                    $.each(item.SubGroups, function (idx, subGroupItem) {
                        var subGroup = $("<optgroup></optgroup>")
                                        .attr("label", subGroupItem.Group);
                        $.each(subGroupItem.Items, function (idx, subItem) {
                            var option = formatMultiSelect(subItem, options.values);
                            subGroup.append(option);
                        });
                        group.append(subGroup);
                    });
                } else {
                    $.each(item.Items, function (idx, item) {
                        var option = formatMultiSelect(item, options.values);
                        group.append(option);
                    });
                }
                $this.append(group);
            });
            $this.multiselect({
                optGroupSelectable: true,
                optGroupCollapsible: true,
                checkAllText: options.checkAllText,
                uncheckAllText: options.uncheckAllText,
                noneSelectedText: options.noneSelectedText,
                selectedText: options.selectedText
            }).multiselect('collapseOptgroups');
        }
    });
};


$.fn.addRequired = function (options) {
    var $this = $(this);
    var defaults = {
        text: 'Поле является обязательным.',
        requiredElement: '<span class="red">*</span>'
    };
    options = $.extend(defaults, options);
    $this.each(function (idx, elem) {
        $this = $(elem);
        $this.rules('add', { required: true, messages: { required: options.text} });
        var td = $this.closest('tr').find('td:first');
        var html = td.html().replace(/(&nbsp;)*/g, '');
        td.html(html);
        td.append($(options.requiredElement));
    });
};

$.fn.removeRequired = function (options) {
    var $this = $(this);
    var defaults = {
        replaceText: '  '
    };
    options = $.extend(defaults, options);
    $this.removeClass('input-validation-error');
    $this.each(function (idx, elem) {
        $this = $(elem);
        $this.rules('remove');
        var td = $this.closest('tr').find('td:first');
        if (td.find("span").length > 0) {
            td.find("span").remove();
            td.append(options.replaceText);
        }
    });
};

function formatMultiSelect(item, values) {
    var option = $("<option></option>")
                                    .attr("value", item.Id)
                                    .attr("valueid", item.Id)
                                    .text(item.Name.Default);
    if ($.inArray(item.Id, values) > -1) {
        option.attr("selected", "selected");
    }
    return option;
}

function getDefaultOption() {
    return $('<option valueId="-1" value=""> - Выбрать - </option>');
}
function getOtherOption() {
    return $('<option valueId="0" value="0"> Другая </option>');
}

function ajaxError(request, type, errorThrown) {
    var message = "There was an error with the AJAX request.\n";
    switch (type) {
        case 'timeout':
            message += "The request timed out.";
            break;
        case 'notmodified':
            message += "The request was not modified but was not retrieved from the cache.";
            break;
        case 'parsererror':
            message += "XML/Json format is bad.";
            break;
        default:
            message += "HTTP Error (" + request.status + " " + request.statusText + request.responseText + ").";
    }
    message += "\n";
    console.log(message);
}
